package com.article.mail;

import java.io.UnsupportedEncodingException;
import java.util.*;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;

public class SendTextEmail {
    public static void main(String[] args) {
        // 收件人电子邮箱
        String to = "1064322591@qq.com";

        //抄送人邮箱
        String cs = "435187576@qq.com,xucong0213@126.com";

        // 发件人电子邮箱
        String from = "xucong0213@126.com";

        // 指定发送邮件的主机为 smtp.126.com
        String host = "smtp.126.com"; // 126 邮件服务器

        // 获取系统属性
        Properties properties = System.getProperties();

        // 设置邮件服务器
        properties.setProperty("mail.smtp.host", host);

        properties.put("mail.smtp.auth", "true");
        // 获取默认session对象
        Session session = Session.getDefaultInstance(properties, new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("xucong0213@126.com", "xxxx"); // 发件人邮件用户名、密码
            }
        });

        try {
            // 创建默认的 MimeMessage 对象
            MimeMessage message = new MimeMessage(session);

            // Set From: 头部头字段
            message.setFrom(new InternetAddress(from));

            // Set To: 头部头字段
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

            //以下是多个收件人
            //if (to != null) {
            //    InternetAddress[] iaToListms = new InternetAddress().parse(to);
            //    message.addRecipients(Message.RecipientType.TO, iaToListms);
            //}

            //抄送收件人Message.RecipientType.CC，密送收件人Message.RecipientType.BCC
            if (cs != null) {
                InternetAddress[] iaToListms = new InternetAddress().parse(cs);
                message.addRecipients(Message.RecipientType.CC, iaToListms);
            }

            // Set Subject: 头部头字段
            message.setSubject("这是邮件标题");

            // 设置消息体
            message.setText("这是邮件内容，哈哈哈哈哈哈");

            // 发送 HTML 消息, 可以插入html标签
            //message.setContent("<h1>This is actual message</h1>",
            //        "text/html" );

            // 发送消息
            Transport.send(message);
            System.out.println("Sent message successfully....");
        } catch (MessagingException mex) {
            mex.printStackTrace();
        }
    }

}